package com.fla.live.im.handler;


import com.fla.live.im.LiveMessageThread;
import com.fla.live.im.RoomManage;
import com.jiai.core.util.SpringUtil;
import com.jiai.core.util.ThreadPoolProxy;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.util.AttributeKey;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatRoomHandler extends ChannelHandlerAdapter{
	public static final AttributeKey<ChatRoomAttr> CHAT_ROOM_ATTR = AttributeKey.valueOf("chat_room.channel");

	/**
	 * 房间用户
	 */
	private static Map<String,Map<String,ChannelHandlerContext>>  contexts=new ConcurrentHashMap<>();
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		
		 getProxy().executeTask(new LiveMessageThread(ctx,msg));
	}
	
	
	@Override
	public void close(ChannelHandlerContext ctx, ChannelPromise promise)
			throws Exception {
		// TODO Auto-generated method stub
		super.close(ctx, promise);
		RoomManage.getInstance().remove(ctx);
	}


	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
	
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelActive(ctx);
	}
	
	private ThreadPoolProxy getProxy(){
		return SpringUtil.getBean(ThreadPoolProxy.class);
	}

}
